# coding=utf8
import time
import redis
import requests
import traceback

from settings import LOCAL_SPIDER_REDIS_NODE
from settings import ONLINE_SPIDER_REDIS_NODE

from tools.logger import Logger
from tools.timing import timing, check_timing
from tools.timing_handler import main as main_timing
from tools.redis_handler import RedisHandler


class SupportRedis(object):
    def __init__(self, error_back=None, **kwargs):
        self.name = "redis支持服务 "
        self.error_back = error_back

    def run(self, logger):
        logger.info("{name}已正式启动。".format(name=self.name))
        redishandler = RedisHandler(startup_node=ONLINE_SPIDER_REDIS_NODE)
        nredishandler = RedisHandler(startup_node=LOCAL_SPIDER_REDIS_NODE)
        # redishandler = redis.Redis(host=ONLINE_SPIDER_REDIS_NODE["host"], port=ONLINE_SPIDER_REDIS_NODE["port"], db=ONLINE_SPIDER_REDIS_NODE["db"])
        # nredishandler = redis.Redis(host=LOCAL_SPIDER_REDIS_NODE["host"], port=LOCAL_SPIDER_REDIS_NODE["port"], db=LOCAL_SPIDER_REDIS_NODE["db"])

        while 1:
            logger.info("{name}正在运行。".format(name=self.name))

            try:
                if redishandler.info(israise=False) is None:
                    redishandler.__init_connect__(startup_node=ONLINE_SPIDER_REDIS_NODE)
                if nredishandler.info(israise=False) is None:
                    nredishandler.__init_connect__(startup_node=LOCAL_SPIDER_REDIS_NODE)

                keys = redishandler.keys()
                for keyi in keys:
                    try:
                        self.execute(redishandler, nredishandler, keyi, logger=logger)
                    except Exception as error:
                        self.error_back.report("{name}在处理{}时报错，{}".format(keyi, error, name=self.name))

            except Exception as error:
                self.error_back.report("{name}在调用时报错，{}".format(error, name=self.name))
                logger.error(traceback.format_exc())

            time.sleep(5)

    def execute(self, redishandler, nredishandler, rediskey, **kwargs):
        logger = kwargs["logger"]

        if isinstance(rediskey, bytes):
            rediskey = rediskey.decode()

        if "public" in rediskey:
            return

        rediskey_type = redishandler.type(rediskey).decode()

        if rediskey_type == "list":
            count = 0
            while 1:
                data = redishandler.lpop(rediskey)
                if isinstance(data, bytes):
                    data = data.decode()

                if data:
                    nredishandler.rpush(rediskey, data)
                    count += 1
                else:
                    break

            logger.info("{name}在处理队列{}时，共移动了{}个数据。".format(rediskey, count, name=self.name))
